package com.dk.file.controller;

import com.dk.file.service.QiniuYunService;
import com.ts.common.core.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

@RestController
@Slf4j
public class UploadController {

    @Autowired
    private QiniuYunService qiniuYunService;

    //文件上传666
    @PostMapping("/fileUpload")
    public Result topicUpload(MultipartFile file){
        String Filename = file.getOriginalFilename();
        String contentType = file.getContentType();
        String url = null;
        try {
            InputStream ips = file.getInputStream();

            log.info("Filename:{}",Filename);
            log.info("contentType:{}",contentType);
            log.info("ips:{}",ips);

            //加入时间戳防止文件同名覆盖
            StringBuffer buffer = new StringBuffer(Filename);
            int index = buffer.lastIndexOf(".");
            buffer.insert(index,"-"+System.currentTimeMillis());

            url = qiniuYunService.upload(buffer.toString(), ips, contentType);
        } catch (IOException e) {
            log.error("文件上传失败",e);
            return new Result().error("文件上传失败");
        }
        return new Result().ok(url);
    }
}
